package cn.wolfcode.luowowo.website.controller;

import cn.wolfcode.luowowo.article.domain.Destination;
import cn.wolfcode.luowowo.article.service.IDestinationService;
import cn.wolfcode.luowowo.article.service.IStrategyCommendService;
import cn.wolfcode.luowowo.article.service.IStrategyDetailService;
import cn.wolfcode.luowowo.article.service.IStrategyTagService;
import cn.wolfcode.luowowo.cache.key.RedisKey;
import cn.wolfcode.luowowo.cache.service.IStrategyStatsCacheService;
import cn.wolfcode.luowowo.cache.vo.StrategyStats;
import cn.wolfcode.luowowo.comment.domain.StrategyComment;
import cn.wolfcode.luowowo.comment.service.IStrategyCommentService;
import cn.wolfcode.luowowo.common.query.StrategyQuery;
import cn.wolfcode.luowowo.common.util.AjaxResult;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.search.query.SearchQueryObject;
import cn.wolfcode.luowowo.search.service.IStrategySearchService;
import cn.wolfcode.luowowo.website.annotation.LoginRequired;
import cn.wolfcode.luowowo.website.annotation.LoginUser;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.data.mongodb.core.mapping.Field;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/strategy")
public class StrategyController {
    @Reference
    private IStrategyDetailService detailService;
    @Reference
    private IStrategyTagService tagService;
    @Reference
    private IDestinationService destinationService;
    @Reference
    private IStrategyCommentService commentService;
    @Reference
    private IStrategyStatsCacheService strategyStatsCacheService;
    @Reference
    private IStrategySearchService strategySearchService;
    @Reference
    private IStrategyCommendService strategyCommendService;

    @RequestMapping("")
    public String index(Model model){
        //飙升排行榜,热门排行榜
        model.addAttribute("upCds",
                strategyStatsCacheService.listRankTop10(RedisKey.STRATEGY_STATS_UP_SORT.getPrefix()));
        model.addAttribute("hotCds",
                strategyStatsCacheService.listRankTop10(RedisKey.STRATEGY_STATS_HOT_SORT.getPrefix()));
        //主题推荐和commends注释掉了,后面再说
        model.addAttribute("commends", strategyCommendService.selectTop5());
        model.addAttribute("themeCds", strategySearchService.commendTheme());
        //构建国内,海外,主题三个高级查询条件
        model.addAttribute("unabroads", strategySearchService.createCondition(SearchQueryObject.CONDITION_UNABROAD));
        model.addAttribute("abroads", strategySearchService.createCondition(SearchQueryObject.CONDITION_ABROAD));
        model.addAttribute("themes", strategySearchService.createCondition(SearchQueryObject.CONDITION_THEME));
        return "strategy/index";
    }

    @RequestMapping("/searchPage")
    public String searchPage(SearchQueryObject qo, Model model){
        //共享更多攻略
        model.addAttribute("page", strategySearchService.searchPage(qo));
        return "strategy/searchPageTpl";
    }

    @RequestMapping("list")
    public String list(@ModelAttribute("qo")StrategyQuery qo, Model model){
        //根据目的地查询所有的标签
        model.addAttribute("tags", tagService.selectTagsByDestId(qo.getDestId()));
        //根据destId和tagId查询得到的pageInfo
        model.addAttribute("pageInfo", detailService.query(qo));
        //共享目的地和吐司
        List<Destination> list = destinationService.toasts(qo.getDestId());
        model.addAttribute("toasts", list);
        model.addAttribute("dest", list.remove(list.size()-1));
        return "strategy/list";
    }

    @RequestMapping("/detail")
    public String detail(Long id, Model model, @LoginUser UserInfo userInfo){
        //在阅读之前就+1,再显示
        strategyStatsCacheService.incr(id, 1, IStrategyStatsCacheService.STRATEGY_STATS_VIEWNUM);
        //显示收藏数,注意,因为可能是没有登录的,所以要判断userinfo
        boolean isFavor = userInfo != null ? strategyStatsCacheService.isFavor(userInfo.getId(), id) : false;
        model.addAttribute("isFavor", isFavor);
        //vo要在上面redis的操作之后再去获取
        model.addAttribute("vo", strategyStatsCacheService.getStatsCache(id));
        model.addAttribute("detail", detailService.selectContainContentById(id));
        //阅读了排行榜对应分数+1
        strategyStatsCacheService.addRank(RedisKey.STRATEGY_STATS_UP_SORT, id, 1);
        return "strategy/detail";
    }

    @LoginRequired
    @RequestMapping("/commentAdd")
    @ResponseBody
    public Object commentAdd(@LoginUser UserInfo userInfo, StrategyComment entity){
        AjaxResult ajaxResult = new AjaxResult();
        try{
            //设置评论者的信息,评论时间
            entity.setUserId(userInfo.getId());
            entity.setUsername(userInfo.getNickname());
            entity.setLevel(userInfo.getLevel());
            entity.setHeadUrl(userInfo.getHeadImgUrl());
            entity.setCreateTime(new Date());
            //保存评论
            ajaxResult = commentService.save(entity);
            //redis还有一个评论数,要存到ajax的data里面去
            strategyStatsCacheService.incr(entity.getDetailId(),
                    1, IStrategyStatsCacheService.STRATEGY_STATS_REPLYNUM);
            ajaxResult.addData(strategyStatsCacheService.getStatsCache(entity.getDetailId()).getReplynum());
            //评论之后要分值+1
            strategyStatsCacheService.addRank(RedisKey.STRATEGY_STATS_UP_SORT, entity.getDetailId(), 1);
        }catch (Exception e){
            ajaxResult.mark(e.getMessage());
        }
        return ajaxResult;
    }

    @RequestMapping("/comment")
    public String comment(StrategyQuery qo, Model model){
        //页面共享page
        model.addAttribute("page", commentService.query(qo));
        return "strategy/commentTpl";
    }
    @LoginRequired
    @RequestMapping("/commentThumbUp")
    @ResponseBody
    public Object commentThumbUp(String toId, Long fromId){
        //访问有两种,一是点赞,二是取消
        return commentService.commentThumbUp(toId, fromId);
    }
    @LoginRequired
    @RequestMapping("/favor")
    @ResponseBody
    public Object favor(Long strategyId, @LoginUser UserInfo userInfo){
        AjaxResult ajaxResult = new AjaxResult();
        //收藏,true表示收藏,false表示取消收藏
        ajaxResult.setSuccess(strategyStatsCacheService.favor(userInfo.getId(), strategyId));
        //设置收藏数回去
        ajaxResult.addData(strategyStatsCacheService.getStatsCache(strategyId).getFavornum());
        //收藏+1, 取消收藏-1
        int num = ajaxResult.isSuccess() ? 1 : -1;
        strategyStatsCacheService.addRank(RedisKey.STRATEGY_STATS_HOT_SORT, strategyId, num);
        return ajaxResult;
    }
    @LoginRequired
    @RequestMapping("/strategyThumbup")
    @ResponseBody
    public Object strategyThumbup(Long strategyId, @LoginUser UserInfo userInfo){
        AjaxResult ajaxResult = new AjaxResult();
        //一天只能点赞一次,返回true表示点赞成功
        ajaxResult.setSuccess(strategyStatsCacheService.thumbsupnum(userInfo.getId(), strategyId));
        //共享点赞数回页面
        ajaxResult.addData(strategyStatsCacheService.getStatsCache(strategyId).getThumbsupnum());
        //成功点赞才会+1,失败不执行
        if (ajaxResult.isSuccess()) {
            strategyStatsCacheService.addRank(RedisKey.STRATEGY_STATS_HOT_SORT, strategyId, 1);
        }
        return ajaxResult;
    }

}
